package com.rfid.a252robot.net;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.rfid.a252robot.net.bean.BookInfoRespon;
import com.rfid.a252robot.net.bean.BookInfoRespon1;
import com.rfid.a252robot.net.bean.TokenRespon;
import com.rfid.common.log.LogUtils;
import com.rfid.manager.TokenManager;
import com.rfid.util.OkHttpUtils;
import com.spectre.generate.ConfigManager;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public enum BookLibApi {

    INSTANCE;
    IBookService mApiService;

    public void init() {
        try {
            String url = "https://report.clcn.net.cn/";
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
                    .client(OkHttpUtils.getClient())
                    .build();
            mApiService = retrofit.create(IBookService.class);
        } catch (Exception e) {
            LogUtils.e(e);
        }
    }

    private String getToken() {
        String token = TokenManager.INSTANCE.getToken();
        if (TextUtils.isEmpty(token)) {
            try {
                token = requestToken();
                TokenManager.INSTANCE.setToken(token);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (TextUtils.isEmpty(token)) {
            token = "eyJ1c2VyTmFtZSI6ImFsZXBoX2FkbWluIn0=";
        }
        return token;
    }

    private String requestToken() throws IOException {
        String secret = "{\"username\":\"aleph_admin\",\"password\":\"admin\"}";
        TokenRespon tokenRespon = mApiService.getToken(secret).execute().body();
        if ("200".equals(tokenRespon.getStatus())) {
            return tokenRespon.getData().getToken();
        }
        return "";
    }

    public BookInfoRespon getBookInfo(String barcode) throws IOException {
        String aat = getToken();
        String apiid = "shlib.folio.searchItemByBarcode";
        String parm = String.format("requestjson={\"barcode\":\"%s\"}",barcode);
        Call<BookInfoRespon> call =  mApiService.getBookInfo(aat,apiid,parm);
        BookInfoRespon respon = call.execute().body();
        return respon;
    }

    public BookInfoRespon1 getBookInfo1(String isbn) throws Exception {
        String url = String.format("http://www.bookcovers.cn/indexc.php?client=clcn&isbn=%s&callback=test",isbn);
        String respon = OkHttpUtils.getRespon(url);
        respon = respon.replace("test(","");
        respon = respon.substring(0,respon.length() - 2);
        Gson gson = new Gson();
        return gson.fromJson(respon,BookInfoRespon1.class);
    }

}
